# -*- coding: UTF-8 -*-
"""
此类是用来进行mysql数据库操作的
"""

import pymysql


class Mysqlhelper:
    # 这是mysql数据库的连接属性
    MYSQL_CONNECT = {
        'MYSQL_HOST': '114.115.219.219',
        'MYSQL_PORT': 3306,
        'MYSQL_DB': 'globallegaldatabase',
        'MYSQL_USER': 'root',
        'MYSQL_PASSWD': 'xinanzhengfadaqxueapp03!',
        'MYSQL_CHARSET': 'utf8'
    }

    def __init__(self):
        self.sqlhost = self.MYSQL_CONNECT['MYSQL_HOST']
        self.sqlport = self.MYSQL_CONNECT['MYSQL_PORT']
        self.sqldb = self.MYSQL_CONNECT['MYSQL_DB']
        self.sqluser = self.MYSQL_CONNECT['MYSQL_USER']
        self.sqlpassword = self.MYSQL_CONNECT['MYSQL_PASSWD']
        self.sqlcharset = self.MYSQL_CONNECT['MYSQL_CHARSET']
        self.sqlconn = pymysql.connect(host=self.sqlhost, port=self.sqlport, db=self.sqldb, user=self.sqluser,
                                       passwd=self.sqlpassword, charset=self.sqlcharset)
        # 创建游标
        self.sqlcursor = self.sqlconn.cursor()

    def close(self):
        self.sqlcursor.close()
        self.sqlconn.close()

    # 增加
    def insert(self, sql):
        return self._edit(sql)

    # 删除
    def delete(self, sql):
        return self._edit(sql)

    # 修改
    def update(self, sql):
        return self._edit(sql)

    # 查询
    def select(self, sql):
        result = 0
        try:
            # 开启连接
            # self.sqlconn
            # 执行游标
            self.sqlcursor.execute(sql)
            result = self.sqlcursor.fetchall()
            # 关闭连接
            self.close()
        except Exception as e:
            # 抛出异常并打印
            print(e)
            raise e
        # 返回结果
        return result

    # 增删改其实都是调用编辑
    def _edit(self, sql):
        count = 0
        try:
            # 开启连接
            # self.sqlconn
            # 执行游标
            count = self.sqlcursor.execute(sql)
            # 提交事物
            self.sqlconn.commit()
            # 关闭连接
            self.close()
        # 捕捉异常
        except Exception as e:
            # 抛出异常并打印
            print(e)
            raise e
        # 返回结果
        return count
